#include "SpellcorrectServer.h"
#include "MyTask.h"
#include "TcpConnection.h"
#include <iostream>
#include <sstream>

using std::stringstream;

SpellcorrectServer::SpellcorrectServer(const string& cfgFileName)
    :_conf(*new Configuration(cfgFileName))
     ,_tcpServer(getTcpConf().first,getTcpConf().second)
     ,_threadpool(getThreadConf().first,getThreadConf().second)
{}

pair<int,int> SpellcorrectServer::getThreadConf()
{
    int threadNum,buffSize;
    stringstream ss;
    auto iter=_conf.getConfigMap().begin();
    iter++;
    string line=iter->first;
    string line2=iter->second;
    ss<<line;ss>>threadNum;
    ss<<line2;ss>>buffSize;
    return make_pair(threadNum,buffSize);
}
pair<string,unsigned short> SpellcorrectServer::getTcpConf()
{
    unsigned short port;
    stringstream ss;
    auto iter=_conf.getConfigMap().begin();
    string ip=iter->first;
    string line=iter->second;
    ss<<line;ss>>port;
    return make_pair(ip,port);

}

void SpellcorrectServer::onConnection(const xkk::TcpConnectionPtr &conn)
{
    cout<<conn->toString()<<" has connected!"<<endl;
    conn->send("Welcome to server!");
}

void SpellcorrectServer::onMessage(const xkk::TcpConnectionPtr &conn)
{
    string msg=conn->receive();
    MyTask task(msg,conn);
    pThreadPool->addTask(bind(&MyTask::response,task));
}
void SpellcorrectServer::onClose(const xkk::TcpConnectionPtr &conn)
{
    cout<<conn->toString()<<" has closed!"<<endl;
}


void SpellcorrectServer::start()
{
    _threadpool.start();
    pThreadPool=&_threadpool;

    _tcpServer.setConnectionCallback(onConnection);
    _tcpServer.setMessageCallback(onMessage);
    _tcpServer.setCloseCallback(onClose);
    
    _tcpServer.start();
}
